import java.util.Stack;

/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer II 038. 每日温度
 * @author: WXY
 * @create: 2022-12-27 18:52
 * @Version 1.0
 **/

public class Num_offer2_038_dailyTemperatures {
    public static int[] dailyTemperatures(int[] temperatures) {
        Stack<Integer> stack = new Stack<>();
        int[] ans = new int[temperatures.length];
        int index = 0;
        boolean flag = false;
        for (int i = 0; i < temperatures.length; i++) {
            while (stack.isEmpty() || temperatures[i] < temperatures[stack.peek()]) {
                stack.push(i);
                flag = true;
               break;
            }
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()] ) {
                int num = stack.pop();
                ans[num] = i - num;

            }
            if (flag == true) {
                flag = false;
            } else {
                stack.push(i);
            }
        }
        return ans;
    }


    public static int[] dailyTemperatures1(int[] temperatures) {
        Stack<Integer> stack = new Stack<>();
        int[] ans = new int[temperatures.length];
        for (int i = 0; i < temperatures.length; i++) {
            while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
                int num = stack.pop();
                ans[num] = i - num;
            }
            stack.push(i);
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{30,60,90};
        int[] ints = dailyTemperatures1(arr);
        for (int n : ints) {
            System.out.print(n + " ");
        }
    }
}
